package com.lys.msmservice.controller;


import com.lys.commonutils.JwtUtils;
import com.lys.commonutils.R;
import com.lys.msmservice.service.MsmService;
import com.lys.msmservice.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@Slf4j
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone){
        //1 从redis获取验证码，如果获取到直接返回
        Object code =  redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2 如果redis获取不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        Map<String,Object> parms = new HashMap<>();
        parms.put("code",RandomUtil.getFourBitRandom());
        log.info("验证码{}",parms);
        boolean ret = msmService.send(parms,phone);
        if(ret) {
            //发送成功，把发送成功验证码放到redis里面
            //将生成的手机验证码信息存入redis中 5分钟
            redisTemplate.opsForValue().set(phone,parms,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }
}
